#!/usr/bin/env node

/**
 * Minecraft面板初始化脚本
 * 用于首次安装时的系统初始化
 */

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

console.log('==========================================');
console.log('  Minecraft面板初始化脚本');
console.log('==========================================');
console.log();

// 检查是否已经初始化
function checkInitialized() {
    const dbPath = path.join(__dirname, 'database.sqlite');
    if (fs.existsSync(dbPath)) {
        console.log('⚠️  检测到数据库文件，系统可能已经初始化');
        console.log('   如果要重新初始化，请删除 database.sqlite 文件');
        process.exit(1);
    }
}

// 创建必要的目录
function createDirectories() {
    const directories = [
        'logs',
        'uploads',
        'backups',
        'temp',
        'public/uploads',
        'public/images'
    ];

    directories.forEach(dir => {
        const dirPath = path.join(__dirname, dir);
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
            console.log(`✅ 创建目录: ${dir}`);
        }
    });
}

// 创建环境配置文件
function createEnvironmentFile() {
    const envPath = path.join(__dirname, '.env');
    const envExamplePath = path.join(__dirname, '.env.example');

    if (!fs.existsSync(envPath) && fs.existsSync(envExamplePath)) {
        // 生成随机密钥
        const sessionSecret = crypto.randomBytes(64).toString('hex');
        
        let envContent = fs.readFileSync(envExamplePath, 'utf8');
        envContent = envContent.replace('your-secret-key-here-change-this-in-production', sessionSecret);
        
        fs.writeFileSync(envPath, envContent);
        console.log('✅ 创建环境配置文件: .env');
    }
}

// 创建日志配置文件
function createLogConfig() {
    const logConfig = {
        "version": 1,
        "disable_existing_loggers": false,
        "formatters": {
            "simple": {
                "format": "%level - %message"
            },
            "detailed": {
                "format": "%level - %timestamp - %logger - %message"
            }
        },
        "appenders": {
            "console": {
                "type": "console",
                "layout": {
                    "type": "pattern",
                    "pattern": "%[%level%] %message%"
                }
            },
            "file": {
                "type": "file",
                "filename": "logs/app.log",
                "maxLogSize": 10485760,
                "numBackups": 5,
                "layout": {
                    "type": "pattern",
                    "pattern": "%d{yyyy-MM-dd hh:mm:ss} [%level] - %message"
                }
            },
            "errorFile": {
                "type": "file",
                "filename": "logs/error.log",
                "maxLogSize": 10485760,
                "numBackups": 5,
                "layout": {
                    "type": "pattern",
                    "pattern": "%d{yyyy-MM-dd hh:mm:ss} [%level] - %message"
                }
            }
        },
        "categories": {
            "default": {
                "appenders": ["console", "file"],
                "level": "info"
            },
            "error": {
                "appenders": ["errorFile"],
                "level": "error"
            }
        }
    };

    const logConfigPath = path.join(__dirname, 'config', 'log4js.json');
    if (!fs.existsSync(path.dirname(logConfigPath))) {
        fs.mkdirSync(path.dirname(logConfigPath), { recursive: true });
    }
    
    fs.writeFileSync(logConfigPath, JSON.stringify(logConfig, null, 2));
    console.log('✅ 创建日志配置文件: config/log4js.json');
}

// 创建Docker配置文件
function createDockerConfig() {
    const dockerConfig = {
        "registry-mirrors": [
            "https://registry.docker-cn.com",
            "https://docker.mirrors.ustc.edu.cn",
            "https://hub-mirror.c.163.com"
        ],
        "log-driver": "json-file",
        "log-opts": {
            "max-size": "100m",
            "max-file": "3"
        },
        "live-restore": true,
        "default-address-pools": [
            {
                "base": "172.80.0.0/16",
                "size": 24
            }
        ]
    };

    const dockerConfigPath = path.join(__dirname, 'config', 'daemon.json');
    if (!fs.existsSync(path.dirname(dockerConfigPath))) {
        fs.mkdirSync(path.dirname(dockerConfigPath), { recursive: true });
    }
    
    fs.writeFileSync(dockerConfigPath, JSON.stringify(dockerConfig, null, 2));
    console.log('✅ 创建Docker配置文件: config/daemon.json');
}

// 创建默认服务器配置
function createServerConfigs() {
    const configs = {
        "vanilla": {
            "image": "registry.docker-cn.com/itzg/minecraft-server",
            "memory": 1024,
            "java_version": "17",
            "properties": {
                "server-port": 25565,
                "motd": "Minecraft Server",
                "max-players": 20,
                "gamemode": "survival",
                "difficulty": "normal",
                "spawn-protection": 0,
                "enable-command-block": true
            }
        },
        "spigot": {
            "image": "registry.docker-cn.com/itzg/minecraft-server",
            "type": "SPIGOT",
            "memory": 1024,
            "java_version": "17",
            "properties": {
                "server-port": 25565,
                "motd": "Spigot Server",
                "max-players": 20,
                "gamemode": "survival",
                "difficulty": "normal",
                "spawn-protection": 0,
                "enable-command-block": true
            }
        },
        "paper": {
            "image": "registry.docker-cn.com/itzg/minecraft-server",
            "type": "PAPER",
            "memory": 1024,
            "java_version": "17",
            "properties": {
                "server-port": 25565,
                "motd": "Paper Server",
                "max-players": 20,
                "gamemode": "survival",
                "difficulty": "normal",
                "spawn-protection": 0,
                "enable-command-block": true
            }
        },
        "forge": {
            "image": "registry.docker-cn.com/itzg/minecraft-server",
            "type": "FORGE",
            "memory": 2048,
            "java_version": "17",
            "properties": {
                "server-port": 25565,
                "motd": "Forge Server",
                "max-players": 20,
                "gamemode": "survival",
                "difficulty": "normal",
                "spawn-protection": 0,
                "enable-command-block": true
            }
        }
    };

    const configPath = path.join(__dirname, 'config', 'server-configs.json');
    if (!fs.existsSync(path.dirname(configPath))) {
        fs.mkdirSync(path.dirname(configPath), { recursive: true });
    }
    
    fs.writeFileSync(configPath, JSON.stringify(configs, null, 2));
    console.log('✅ 创建服务器配置文件: config/server-configs.json');
}

// 创建启动脚本
function createStartupScript() {
    const startScript = `#!/bin/bash

# Minecraft面板启动脚本

cd "$(dirname "$0")"

# 检查Node.js是否安装
if ! command -v node &> /dev/null; then
    echo "错误: 未找到Node.js，请先安装Node.js"
    exit 1
fi

# 检查npm是否安装
if ! command -v npm &> /dev/null; then
    echo "错误: 未找到npm，请先安装npm"
    exit 1
fi

# 检查依赖是否安装
if [ ! -d "node_modules" ]; then
    echo "安装依赖包..."
    npm install --production
fi

# 启动应用
echo "启动Minecraft面板..."
node app.js
`;

    const scriptPath = path.join(__dirname, 'start.sh');
    fs.writeFileSync(scriptPath, startScript);
    fs.chmodSync(scriptPath, '755');
    console.log('✅ 创建启动脚本: start.sh');
}

// 创建Windows启动脚本
function createWindowsStartupScript() {
    const startScript = `@echo off
chcp 65001 >nul
cd /d "%~dp0"

:: 检查Node.js是否安装
where node >nul 2>&1
if %errorLevel% neq 0 (
    echo 错误: 未找到Node.js，请先安装Node.js
    pause
    exit /b 1
)

:: 检查npm是否安装
where npm >nul 2>&1
if %errorLevel% neq 0 (
    echo 错误: 未找到npm，请先安装npm
    pause
    exit /b 1
)

:: 检查依赖是否安装
if not exist "node_modules" (
    echo 安装依赖包...
    npm install --production
)

:: 启动应用
echo 启动Minecraft面板...
node app.js

pause
`;

    const scriptPath = path.join(__dirname, 'start.bat');
    fs.writeFileSync(scriptPath, startScript);
    console.log('✅ 创建Windows启动脚本: start.bat');
}

// 创建系统检查脚本
function createSystemCheckScript() {
    const checkScript = `#!/usr/bin/env node

const os = require('os');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

console.log('==========================================');
console.log('  Minecraft面板系统检查');
console.log('==========================================');
console.log();

// 检查操作系统
console.log('🖥️  操作系统信息:');
console.log(`   平台: ${os.platform()}`);
console.log(`   架构: ${os.arch()}`);
console.log(`   版本: ${os.release()}`);
console.log(`   内存: ${Math.round(os.totalmem() / 1024 / 1024 / 1024)}GB`);
console.log(`   CPU核心: ${os.cpus().length}`);
console.log();

// 检查Node.js版本
console.log('📦 Node.js环境:');
try {
    const nodeVersion = execSync('node --version', { encoding: 'utf8' }).trim();
    const npmVersion = execSync('npm --version', { encoding: 'utf8' }).trim();
    console.log(`   Node.js版本: ${nodeVersion}`);
    console.log(`   npm版本: ${npmVersion}`);
    
    // 检查版本要求
    const nodeMajor = parseInt(nodeVersion.slice(1).split('.')[0]);
    if (nodeMajor < 16) {
        console.log('   ❌ Node.js版本过低，建议使用16.0.0以上版本');
    } else {
        console.log('   ✅ Node.js版本符合要求');
    }
} catch (error) {
    console.log('   ❌ 未找到Node.js');
}
console.log();

// 检查Docker
console.log('🐳 Docker环境:');
try {
    const dockerVersion = execSync('docker --version', { encoding: 'utf8' }).trim();
    console.log(`   Docker版本: ${dockerVersion}`);
    console.log('   ✅ Docker已安装');
} catch (error) {
    console.log('   ❌ 未找到Docker，请先安装Docker');
}
console.log();

// 检查必要目录
console.log('📁 目录检查:');
const requiredDirs = ['logs', 'uploads', 'backups', 'public/uploads'];
requiredDirs.forEach(dir => {
    const dirPath = path.join(__dirname, dir);
    if (fs.existsSync(dirPath)) {
        console.log(`   ✅ ${dir} 目录存在`);
    } else {
        console.log(`   ❌ ${dir} 目录不存在`);
    }
});
console.log();

// 检查配置文件
console.log('⚙️  配置文件检查:');
const configFiles = ['.env', 'config/log4js.json', 'config/server-configs.json'];
configFiles.forEach(file => {
    const filePath = path.join(__dirname, file);
    if (fs.existsSync(filePath)) {
        console.log(`   ✅ ${file} 文件存在`);
    } else {
        console.log(`   ❌ ${file} 文件不存在`);
    }
});
console.log();

// 检查端口占用
console.log('🔌 端口检查:');
const port = 3000;
try {
    const net = require('net');
    const server = net.createServer();
    server.listen(port, () => {
        server.close();
        console.log(`   ✅ 端口 ${port} 可用`);
    });
    server.on('error', () => {
        console.log(`   ❌ 端口 ${port} 被占用`);
    });
} catch (error) {
    console.log(`   ❌ 无法检查端口 ${port}`);
}
console.log();

console.log('==========================================');
console.log('  系统检查完成');
console.log('==========================================');
`;

    const scriptPath = path.join(__dirname, 'scripts', 'system-check.js');
    if (!fs.existsSync(path.dirname(scriptPath))) {
        fs.mkdirSync(path.dirname(scriptPath), { recursive: true });
    }
    fs.writeFileSync(scriptPath, checkScript);
    fs.chmodSync(scriptPath, '755');
    console.log('✅ 创建系统检查脚本: scripts/system-check.js');
}

// 主初始化函数
function initialize() {
    console.log('🚀 开始初始化Minecraft面板...');
    console.log();

    try {
        checkInitialized();
        createDirectories();
        createEnvironmentFile();
        createLogConfig();
        createDockerConfig();
        createServerConfigs();
        createStartupScript();
        createWindowsStartupScript();
        createSystemCheckScript();

        console.log();
        console.log('==========================================');
        console.log('  ✅ 初始化完成！');
        console.log('==========================================');
        console.log();
        console.log('📋 下一步操作:');
        console.log('   1. 运行 npm install 安装依赖包');
        console.log('   2. 运行 node app.js 启动面板');
        console.log('   3. 访问 http://localhost:3000/init 进行初始化设置');
        console.log();
        console.log('🔧 有用的命令:');
        console.log('   npm start          - 启动面板');
        console.log('   npm run dev        - 开发模式启动');
        console.log('   node scripts/system-check.js - 系统检查');
        console.log('   ./start.sh         - Linux/Mac启动脚本');
        console.log('   start.bat          - Windows启动脚本');
        console.log();

    } catch (error) {
        console.error('❌ 初始化失败:', error.message);
        process.exit(1);
    }
}

// 运行初始化
initialize();